package com.xnchat.pro.service;

import cn.hutool.core.lang.Console;
import com.xnchat.pro.thread.ClockExecuter;
import com.xnchat.pro.utils.NormalReturn;
import com.xnchat.pro.vo.DelayObject;
import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.concurrent.DelayQueue;

/**
 * @author 小凝
 */
@Service
public class ClockService {
    private static final DelayQueue<DelayObject<String>> delayQueue=new DelayQueue<>();
    private static final HashSet<String> nameSet=new HashSet<>();

    /**
     * 添加clock的方法，消息会根据session自动发
     * @param name
     * @param time
     * @param session
     * @param id
     * @return
     */
    public NormalReturn addClock(String name, int time, String session, int id){
        while (delayQueue.peek()!=null){
            DelayObject<String> poll = delayQueue.poll();
            if(poll!=null){
                nameSet.remove(poll.getT());
            }else {
                break;
            }
        }
        for (String v:nameSet){
            if(v.equals(name)){
                return NormalReturn.FAIL.addMessage("已经添加过啦");
            }
        }
        if(time<3){
            return NormalReturn.FAIL.addMessage("要走直接走谢谢");
        }else if(time>30){
            return NormalReturn.FAIL.addMessage("请安心工作！");
        }

        try {
            ClockExecuter.registJobThread(name, time, session, id);
            delayQueue.add(new DelayObject<>(time*60*1000,name));
            nameSet.add(name);
        }catch (Exception e ){
            Console.error(e);
            return NormalReturn.FAIL.addMessage("未知错误(其实我知道但是不想让你知道)");
        }
        return NormalReturn.SUCCESS.addMessage("马上就要下班了呢！");
    }

    /**
     * 把这个任务关掉
     * @param id
     * @return
     */
    public NormalReturn stopClock(int id){
        ClockExecuter.removeThread(id,"手动终止");
        nameSet.clear();
        delayQueue.clear();
        return NormalReturn.SUCCESS.addMessage("看在你这么惨的份上，伟大的小凝就勉为其难的帮你把提醒关上了吧");
    }


}
